<?php

class ProductController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	// public $layout='//layouts/column2';
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		$accessRules = array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
		);
		$admin = User::model()->getAdminInfo();
		$superadmin = User::model()->getSuperAdminInfo();
		foreach ($admin as $value) {
			$accessRules[] = array('allow', // allow admin user to perform 'admin','create','update','delete' actions
				'actions'=>array('index','view','create','update','delete'),
				'users'=>array($value->username));
		}
		foreach ($superadmin as $value) {
			$accessRules[] = array('allow', // allow superadmin user to perform 'admin','create','update','delete' actions
				'actions'=>array('index','view','admin','create','update','delete'),
				'users'=>array($value->username));
		}
		//Quan trọng phần deny này phải ở cuối cùng của arrary acccessRules
		$accessRules[] = array('deny',  // deny all users
					'users'=>array('*'),
				);
		return $accessRules;
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$category = Category::model()->find(array(
		    'select'=>'categorys_name',
		    'condition'=>'id='.$this->loadModel($id)->category_id)
		);
		$productimage = ProductImage::model()->findByAttributes(array('product_id'=>$id));
		$sql = "SELECT * FROM product WHERE product.category_id = ". $this->loadModel($id)->category_id .' and product.id <> '.$id.' order by created DESC limit 5';
		$related_products = Yii::app()->db->createCommand($sql)->queryAll();

		$this->render('view',array(
			'model'=>$this->loadModel($id), 'category_name' => $category->categorys_name, 'related_products' => $related_products, 'productimage' => $productimage
		));
	}
	/**
	* @param image input, categoryName
	* @return link image da chuyen sang MD5
	*/
	function converImage($imageInput=null)
	{
		$date = date("D M d, Y G:i s");
		if($imageInput) {
			return str_shuffle(md5($imageInput.$date)).'.'.$imageInput->extensionName;
		} else {
			return null;
		}
	}
	/**
	* @param imageName, image input
	* @return save image vao folder tuong ung
	*/
	function saveImage($imageName=null, $imageInput=null)
	{
		if ($imageName && $imageInput) {
			$imageInput->saveAs(Yii::app()->basePath."/../images/product/".$imageName);
		}
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Product;
		$modelImage = new ProductImage;
		$listCategory = Category::model()->getArraryIdCategoryName();
		if (count($listCategory) > 0) {
			if(isset($_POST['Product']))
			{
				$model->attributes=$_POST['Product'];
				$image = CUploadedFile::getInstance($model,'image_link');
				$model->image_link = $this->converImage($image);
				$imageProduct1 = CUploadedFile::getInstance($modelImage,'image_1');
				$modelImage->image_1 = $this->converImage($imageProduct1);
				$imageProduct2 = CUploadedFile::getInstance($modelImage,'image_2');
				$modelImage->image_2 = $this->converImage($imageProduct2);
				$imageProduct3 = CUploadedFile::getInstance($modelImage,'image_3');
				$modelImage->image_3 = $this->converImage($imageProduct3);
				$imageProduct4 = CUploadedFile::getInstance($modelImage,'image_4');
				$modelImage->image_4 = $this->converImage($imageProduct4);

				$category_image_link = Category::model()->findByPk($model->category_id);
				if($model->save()) {
					$this->saveImage($model->image_link,$image);
					// print_r(Yii::app()->db->getLastInsertId());exit(); trả về id của product vừa lưu ở trên
					$product_id = Yii::app()->db->getLastInsertId();
					$modelImage->product_id = $product_id;
					if ($modelImage->save()) {
						$this->saveImage($modelImage->image_1,$imageProduct1);
						$this->saveImage($modelImage->image_2,$imageProduct2);
						$this->saveImage($modelImage->image_3,$imageProduct3);
						$this->saveImage($modelImage->image_4,$imageProduct4);
					}
					$this->redirect(array('view','id'=>$model->id));
				}
			}
			$this->render('create',array(
				'model'=>$model,'modelImage'=>$modelImage,'listCategory'=>$listCategory
			));
		} else {
			$this->redirect(array('category/create'));
		}
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$listCategory = Category::model()->getArraryIdCategoryName();
		$model=Product::model()->findByPk($id);
		$modelImage = ProductImage::model()->findByAttributes(array('product_id'=>$id));
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Product']))
		{
			$model->attributes=$_POST['Product'];
			$image = CUploadedFile::getInstance($model,'image_link');
			if ($this->converImage($image)) {
				$model->image_link = $this->converImage($image);
			}
			$imageProduct1 = CUploadedFile::getInstance($modelImage,'image_1');
			if ($this->converImage($imageProduct1)) {
				$modelImage->image_1 = $this->converImage($imageProduct1);
			}
			$imageProduct2 = CUploadedFile::getInstance($modelImage,'image_2');
			if ($this->converImage($imageProduct2)) {
				$modelImage->image_2 = $this->converImage($imageProduct2);
			}
			$imageProduct3 = CUploadedFile::getInstance($modelImage,'image_3');
			if ($this->converImage($imageProduct3)) {
				$modelImage->image_3 = $this->converImage($imageProduct3);
			}
			$imageProduct4 = CUploadedFile::getInstance($modelImage,'image_4');
			if ($this->converImage($imageProduct4)) {
				$modelImage->image_4 = $this->converImage($imageProduct4);
			}
			//Save
			if($model->save()) {
				$this->saveImage($model->image_link,$image);
				if ($modelImage->save()) {
					$this->saveImage($modelImage->image_1,$imageProduct1);
					$this->saveImage($modelImage->image_2,$imageProduct2);
					$this->saveImage($modelImage->image_3,$imageProduct3);
					$this->saveImage($modelImage->image_4,$imageProduct4);
				}
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,'modelImage'=>$modelImage,'listCategory'=>$listCategory
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Product');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Product('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Product']))
			$model->attributes=$_GET['Product'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Product the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Product::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Product $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='product-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
